package com.store.controller;

import com.store.pojo.Category;
import com.store.service.CategoryService;
import com.store.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;


    @RequestMapping("/toList")
    public String list(Model model){
        //使用业务层对象调用业务层方法
        //绑定总页数
        List<Category> list = categoryService.findAllCategoryInfo();
        //将集合绑定返回到页面
        model.addAttribute("categoryList",list);
        return "adminpage/category-list";
    }


    //添加商品类型信息
    @RequestMapping("/addCategory")
    @ResponseBody
    public Map<String,Object> addCategory(Category category) {
        Map<String ,Object> map = categoryService.addCategoryInfo(category);
        return map;
    }



    @RequestMapping("/deleteById")
    public String deleteById(int id, HttpServletResponse response) throws IOException {
        //使用业务层对象调用业务方法
        int row = categoryService.deleteCategoryInfoById(id);
        if (row<=0){
            //失败弹窗
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("<script>alert('删除失败');location.href='/category/toList';</script>");
            writer.close();
        }
        //成功应该刷新列表页面
        return "redirect:/category/toList";
    }

    //根据id查询当前信息显示到修改页面
    @RequestMapping("/findCategoryByIdToUpdatePage")
    public String findCategoryByIdToUpdatePage(Integer id, HttpSession session){
        //使用业务对象调用业务层方法
        Category category = categoryService.findCategoryById(id);
        //绑定数据
        session.setAttribute("category",category);
        return "adminpage/category-edit";
    }

    @RequestMapping("/doUpdate")
    public String doUpdate(Category category,HttpServletResponse response) throws IOException {
        int row = categoryService.updateCategory(category);
        if (row<=0) {//失败
            //停留在添加页面绑定数据回到页面,使用Model对象绑定数据
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println("<script>alert('修改失败);location.href='/findOrderByIdToUpdatePage';</script>");
            return "redirect:/category/toList";
        }
        //跳转到列表页面
        //model.addAttribute("msg","更新成功");
        return "redirect:/category/toList";//重定向
    }


}
